package com.lglbc.streamer;

import com.lglbc.hello.Mode;
import com.lglbc.hello.OpenAPIGrpc;
import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;
import io.grpc.stub.StreamObserver;

public class Client {
    public static void main(String[] args) {
        ManagedChannel channel = ManagedChannelBuilder.forAddress("localhost", 9090)
                .usePlaintext()
                .build();

        OpenAPIGrpc.OpenAPIStub stub = OpenAPIGrpc.newStub(channel);

        Mode.Request request = Mode.Request.newBuilder()
                .setName("乐哥聊编程")
                .build();
        StreamObserver<Mode.Response> responseObserver = new StreamObserver<Mode.Response>() {
            @Override
            public void onNext(Mode.Response response) {
                System.out.println("Received response: " + response.getMessage());
            }

            @Override
            public void onError(Throwable t) {
                System.err.println("Error: " + t.getMessage());
            }

            @Override
            public void onCompleted() {
                System.out.println("Server completed.");
            }
        };
        StreamObserver<Mode.Request> requestObserver = stub.bidirectionalStreaming(responseObserver);


        for (int i = 0; i < 5; i++) {
            Mode.Request request2 = Mode.Request.newBuilder()
                    .setName("Request " + (i + 1))
                    .build();
            requestObserver.onNext(request2);
        }

        // 结束请求流
        requestObserver.onCompleted();

        // 等待完成
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        channel.shutdown();
    }

}
